package com.sun.kamun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sun.kamun.config.RabbitMQConfig;
import com.sun.kamun.entity.OrderDetails;
import com.sun.kamun.entity.Product;
import com.sun.kamun.entity.User;
import com.sun.kamun.service.OrderService;
import com.sun.kamun.service.ProductService;
import com.sun.kamun.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/order")
@Slf4j
@EnableRabbit
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 添加订单信息
     */
    @PostMapping("insertOrder")
    public String insertOrderDetails(@RequestBody OrderDetails orderDetailsAdd, HttpServletRequest request) {
        //获取当前登录用户的真实姓名,并赋值为联系人名称
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            // 用户未登录，返回未授权错误
            return "error";
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, user.getUserName());
        User one = userService.getOne(wrapper);

        // 使用 UUID 生成订单ID
        String orderId = UUID.randomUUID().toString();
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 拼接日期到订单ID中
        String datePart = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        orderId += datePart;
        //new一个订单对象
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.setOrderId(orderId);
        orderDetails.setUserId(one.getUserId());
        orderDetails.setContactName(one.getUserRealname());
        orderDetails.setContactPhone(one.getUserPhone());
        orderDetails.setCreatedTime(new Date());
        //设置为待发货状态
        orderDetails.setOrderStatus(0);
        //订单总金额
        orderDetails.setOrderTotal(orderDetailsAdd.getOrderTotal());
        orderDetails.setPaymentMethod(orderDetailsAdd.getPaymentMethod());

        //根据商品名称查询商品ID
        LambdaQueryWrapper<Product> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Product::getProductName, orderDetailsAdd.getProductName());
        Product productServiceOne = productService.getOne(lambda);

        //获得ID放入订单表
        orderDetails.setProductId(productServiceOne.getProductId());
        orderDetails.setProductName(orderDetailsAdd.getProductName());
        //获取商品单价
        orderDetails.setProductPrice(productServiceOne.getProductPrice());
        orderDetails.setProductQuantity(orderDetailsAdd.getProductQuantity());
        //设置备注信息
        orderDetails.setShippingAddress(orderDetailsAdd.getShippingAddress());

        boolean save = orderService.save(orderDetails);
        if (save) {
            return "orderdetails";
        } else {
            return "error";
        }

    }


    /**
     * 用户端---查询订单(只返回用户自己下单的订单)
     */

    @GetMapping("/listBySelf")
    public String getOrder(Model model, HttpServletRequest request) {
        //获取当前登录用户的真实姓名,并赋值为联系人名称
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 用户未登录，返回未授权错误
            return "error";
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, user.getUserName());
        User one = userService.getOne(wrapper);
        LambdaQueryWrapper<OrderDetails> lqw = new LambdaQueryWrapper<>();
        //按时间倒序输出订单
        lqw.eq(OrderDetails::getUserId, one.getUserId()).orderByDesc(OrderDetails::getCreatedTime);
        //只返回当前用户的订单
        List<OrderDetails> list = orderService.list(lqw);
        model.addAttribute("orders", list);
        return "orderdetails";
    }

    /**
     * 用户端---处理需要发货的订单
     */
    @PutMapping("orderSend/{orderId}")
    public String sendOrder(@PathVariable String orderId , @RequestBody OrderDetails orderDetails) {
        OrderDetails details=orderService.getById(orderId);
        log.info("当前发货订单id为: "+orderId);
        details.setOrderStatus(1);
        boolean b = orderService.updateById(details);
        if (b) {
            return "redirect:/order/selectOrderSend";
        } else {
            return "error";
        }
    }

    /**
     * 用户端---返回需要发货的订单
     */
    @GetMapping("selectOrderSend")
    public String selectOrder(Model model, HttpServletRequest request) {
        //获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 用户未登录，返回未授权错误
            return "error";
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, user.getUserName());
        User one = userService.getOne(wrapper);
        // 查询待发货的订单列表
        LambdaQueryWrapper<OrderDetails> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(OrderDetails::getOrderStatus, 0); // 选择待发货的订单
        List<OrderDetails> orderList = orderService.list(orderWrapper);

        List<OrderDetails> filteredList = new ArrayList<>();

        for (OrderDetails order : orderList) {
            int productId = order.getProductId();

            // 根据商品ID查询商品信息
            Product product = productService.getById(productId);
            if (product != null && product.getProductUserId() == one.getUserId()) {
                // 如果商品存在且对应的用户ID等于当前登录用户的ID，则加入筛选列表
                filteredList.add(order);
            }
        }

        model.addAttribute("orders", filteredList);
        model.addAttribute("requestType", "delivery"); // 传递请求类型给前端
        return "orderdetails";
    }


    /**
     * 稍后支付---超时订单取消功能
     * */
    @PostMapping("/pendingPayment")
    public String pendingPayment(@RequestBody OrderDetails orderDetailsAdd, HttpServletRequest request) {
        //获取当前登录用户的真实姓名,并赋值为联系人名称
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            // 用户未登录，返回未授权错误
            return "error";
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, user.getUserName());
        User one = userService.getOne(wrapper);

        // 使用 UUID 生成订单ID
        String orderId = UUID.randomUUID().toString();
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        // 拼接日期到订单ID中
        String datePart = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        orderId += datePart;
        //new一个订单对象
        OrderDetails orderDetails = new OrderDetails();
        orderDetails.setOrderId(orderId);
        orderDetails.setUserId(one.getUserId());
        orderDetails.setContactName(one.getUserRealname());
        orderDetails.setContactPhone(one.getUserPhone());
        orderDetails.setCreatedTime(new Date());
        //设置为待发货状态
        orderDetails.setOrderStatus(3);
        //订单总金额
        orderDetails.setOrderTotal(orderDetailsAdd.getOrderTotal());
        orderDetails.setPaymentMethod(orderDetailsAdd.getPaymentMethod());

        //根据商品名称查询商品ID
        LambdaQueryWrapper<Product> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Product::getProductName, orderDetailsAdd.getProductName());
        Product productServiceOne = productService.getOne(lambda);

        //获得ID放入订单表
        orderDetails.setProductId(productServiceOne.getProductId());
        orderDetails.setProductName(orderDetailsAdd.getProductName());
        //获取商品单价
        orderDetails.setProductPrice(productServiceOne.getProductPrice());
        orderDetails.setProductQuantity(orderDetailsAdd.getProductQuantity());
        //设置备注信息
        orderDetails.setShippingAddress(orderDetailsAdd.getShippingAddress());

        boolean save = orderService.save(orderDetails);
        if (save) {
            // 发送订单超时消息
            sendOrderTimeoutMessage(orderDetails);
            return "productlist";
        } else {
            return "error";
        }
    }

    @PostMapping("/confirm")
    public String payOrder(@RequestParam String orderId) {
        // 根据订单ID查询订单信息
        OrderDetails order = orderService.getById(orderId);

        // 检查订单状态是否为待付款
        if (order.getOrderStatus() == 3) {
            // 更新订单状态为待发货
            order.setOrderStatus(0); // 0表示待发货状态
            boolean updateSuccess = orderService.updateById(order);

            if (updateSuccess) {
                return "orderdetails";
            } else {
                return "error";
            }
        } else {
            return "error";
        }
    }


//    @PostMapping("/order/cancel")
//    public String cancelOrder(@RequestParam String orderId) {
//        // 执行取消订单的逻辑
//        boolean cancelSuccess = orderService.cancelOrder(orderId);
//        if (cancelSuccess) {
//            return "success";
//        } else {
//            return "failure";
//        }
//    }


    /**
     * 发送订单超时消息到队列
     */
    private void sendOrderTimeoutMessage(OrderDetails orderDetails) {
        rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_EXCHANGE, RabbitMQConfig.ORDER_ROUTING, orderDetails, message -> {
            // 设置消息过期时间为订单超时时间
            message.getMessageProperties().setExpiration("60000*60"); // 设置订单过期时间一小时
            return message;
        });
    }
}
